package org.west.sky.scripture.strategy.springboot.two;

import org.springframework.stereotype.Component;
import org.west.sky.scripture.strategy.springboot.one.Command;

import java.util.Map;
import java.util.Optional;

/**
 * @author chenghz
 * @date 2022/6/17 14:20
 * @description:
 */
@Component
public class CommandFactory {

    private Map<String, Command> commandMap;

    /**
     * Spring会自动将Strategy接口的实现类注入到这个Map中，key为bean id，value值则为对应的策略实现类
     */
//    @Autowired
    public CommandFactory(Map<String, Command> commandMap) {
        this.commandMap = commandMap;
    }

    /**
     * 执行计算
     *
     * @param operator
     * @param a
     * @param b
     * @return
     */
    public int calculate(String operator, int a, int b) {
        Command command = Optional.ofNullable(commandMap.get(operator))
                .orElseThrow(() -> new IllegalArgumentException("Invalid operator"));
        return command.execute(a, b);
    }
}
